package cn.cas.mango.util.dbscanHot;

import co.elastic.clients.elasticsearch._types.SortOrder;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 簇中的元素类
 */
@lombok.Data
@Slf4j
public class Data {
    private String id;

    private final Set<String> keywords;

    private final Set<String> entities;

    private Date newsPublicDate;

    private boolean visited;

    private boolean added;

    public void setAdded() {
        this.added = true;
    }

    public void setVisited() {
        this.visited = true;
    }

    public Data() {
        keywords = new LinkedHashSet<>();
        entities = new LinkedHashSet<>();
        visited = false;
    }

    public Data(String id) {
        this();
        this.id = id;
    }

    public Data(String id, Set<String> keywords, Set<String> entities,
                String newsPublicDate) {
        this(id);
        this.keywords.addAll(keywords);
        this.entities.addAll(entities);
        try {
            this.newsPublicDate = new SimpleDateFormat("yyyy-MM-dd").parse(newsPublicDate);
        } catch (ParseException e) {
          try {
            this.newsPublicDate = new SimpleDateFormat("yyyy-MM-dd").parse("2010-01-01");
          } catch (ParseException ex) {
            throw new RuntimeException(ex);
          }
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Data)) return false;
        Data data = (Data) o;
        return Objects.equals(keywords, data.keywords);
    }

    @Override
    public int hashCode() {
        return Objects.hash(keywords);
    }

    /**
     * 计算相似度
     * @param data2，要与当前类
     * @return
     */
    public double calSim(Data data2) {
        Set<String> values2 = data2.keywords;
        double inter = calInter(values2).size();
        double union = calUnion(values2).size();
        double sim = (inter + 0.01) / (union + 0.01);
        if (keywords.isEmpty() || data2.keywords.isEmpty()) {
          sim = 0;
        }
        return sim;
    }

    private Set<String> calUnion(Set<String> value2) {
        Set<String> strings = new HashSet<>(keywords);
        strings.addAll(value2);
//        strings.addAll(keywords);
        return strings;
    }

    private Set<String> calInter(Set<String> values2) {
        Set<String> strings = new HashSet<>(keywords);
        strings.retainAll(values2);
        return strings;
    }

}
